#include <unistd.h>

#include "picDeleteLoop.h"
#include "sqlLoop.h"
#include "cJSON.h"

#define DELETE_NUM_ONE_TIME 3

/*
*@描述：删除图片用.
*/
static uv_async_t pic_delete;
static void DeletePicExec(uv_async_t *handle);

void startPicDeleteWork()
{
    uv_loop_t *loop = getPicDeleteLoop();
    uv_async_init(loop, &pic_delete, DeletePicExec);
    uv_run(loop, UV_RUN_DEFAULT);
}

static void noticeDeletePicToSqlite(uint8_t picName[PIC_FILENAME_MAX_LEN])
{
    SqlAsyncCmd cmd = {0};

    cmd.cmdType = SQL_CMD_TYPE_UPDATE;
    cmd.updateType = SQL_CMD_UPDATE_DELETE_COL;
    memcpy(cmd.picName, picName, PIC_FILENAME_MAX_LEN);

    Packet *packTmp = PacketMalloc(sizeof(SqlAsyncCmd));
    copy_packet(packTmp, sizeof(SqlAsyncCmd), (uint8_t *)&cmd);
    sqlEnqueue(packTmp);
    dispatchSqlCmdExec();
}

static void DeletePicExec(uv_async_t *handle)
{
    //                 "\trm $fileName\n"
    LOG_NOTICE("图片数量超过50个, 尝试删除照片");
    uint8_t cmd[1024] = {0};
    sprintf(cmd, "int=0\n"
                 "cd %s\n"
                 "for fileName in `ls -rt .`\n"
                 "do\n"
                 "\tfileName=`echo $fileName|sed 's/\\.jpg//g'`\n"
                 "\tint=`expr $int + 1`\n"
                 "\tstr=\"$str,\\\"$fileName\\\"\"\n"
                 "\tif [ $int -gt %d ]\n"
                 "\t\tthen\n"
                 "\t\t\tbreak\n"
                 "\tfi\n"
                 "done\n"
                 "len=${#str}\n"
                 "echo \"[\"`expr substr $str 2 $len`\"]\"",
            IMG_SAVE_DIR, DELETE_NUM_ONE_TIME);

    // LOG_INFO("%s", cmd);

// (42图片名长度 + 2引号长度 + 1逗号长度) * (DELETE_NUM_ONE_TIME + 1会多删一张) +2[]符号长度 + 1\n长度
#define P_RESULT_SIZE (42 + 2 + 1) * (DELETE_NUM_ONE_TIME + 1) + 2 + 1
    FILE *pFile = popen(cmd, "r");
    uint8_t pResult[P_RESULT_SIZE] = {0};
    if (!pFile)
    {
        LOG_ERROR("popen失败：%s", strerror(errno));
    }
    else
    {
        fgets(pResult, P_RESULT_SIZE, pFile);
        pclose(pFile);
    }

    cJSON *root = cJSON_Parse(pResult);

    if (root == NULL)
    {
        LOG_ERROR("json解析失败");
    }
    else
    {
        cJSON *ele;
        uint8_t *fileNameTmp;
        cJSON_ArrayForEach(ele, root)
        {
            uint8_t deleteFileName[PIC_FILENAME_MAX_LEN] = {0};
            fileNameTmp = cJSON_GetStringValue(ele);
            memcpy(deleteFileName, fileNameTmp, strlen(fileNameTmp));

            char tmp_filename_path[PIC_FILENAME_MAX_LEN * 2] = {0};
            sprintf(tmp_filename_path, "%s/%s.jpg", IMG_SAVE_DIR, deleteFileName);
            if (unlink(tmp_filename_path) < 0)
            {
                LOG_ERROR("删除图片:%s.jpg失败：%s", deleteFileName, strerror(errno));
            }
            else
            {
                LOG_INFO("删除图片:%s.jpg成功", deleteFileName);
                noticeDeletePicToSqlite(deleteFileName);
            }
        }

        cJSON_Delete(root);
    }

#undef P_RESULT_SIZE

    int imgsNum = getFilesNum(IMG_SAVE_DIR);
    if (imgsNum > 50)
    {
        // LOG_ERROR("删除图片失败");
        return;
    }
}
void dispatchDeletePicExec()
{
    // LOG_INFO("触发删除图片通知");
    uv_async_send(&pic_delete);
}
